import 'package:flutter/material.dart';

/// @Date 2024/12/05 18:20
/// @author chris
/// @desc inherited widget demo
///

class TestInheritWidget extends StatefulWidget {
  const TestInheritWidget({super.key});

  @override
  State<TestInheritWidget> createState() => _TestInheritWidgetState();
}

class _TestInheritWidgetState extends State<TestInheritWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "test inherited widget",
        ),
      ),
      body: Column(
        children: [
          Foo(),
          ElevatedButton(
            onPressed: () {
              ThemeColorBox? box =
                  context.getInheritedWidgetOfExactType<ThemeColorBox>();
            },
            child: Text("随机颜色"),
          ),
        ],
      ),
    );
  }
}

class Foo extends StatefulWidget {
  const Foo({super.key});

  @override
  State<Foo> createState() => _FooState();
}

class _FooState extends State<Foo> {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 100,
      height: 100,
      color: ThemeColorBox.of(context).color,
    );
  }
}

class ThemeColorBox extends InheritedWidget {
  const ThemeColorBox(
      {super.key, this.color = Colors.black, required super.child});

  final Color color;

  static ThemeColorBox of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<ThemeColorBox>()!;
  }

  static ThemeColorBox? maybeOf(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<ThemeColorBox>();
  }

  @override
  bool updateShouldNotify(covariant ThemeColorBox oldWidget) {
    return oldWidget.color != color;
  }
}
